package com.wtwd.campus.jdzc.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wtwd.campus.common.RespCode;
import com.wtwd.campus.constant.SignConstant;
import com.wtwd.campus.entity.Classes;
import com.wtwd.campus.entity.Student;
import com.wtwd.campus.entity.Teacher;
import com.wtwd.campus.jdzc.dao.JdzcClassMapper;
import com.wtwd.campus.jdzc.dao.JdzcStudentMapper;
import com.wtwd.campus.jdzc.dao.JdzcTeacherMapper;
import com.wtwd.campus.jdzc.service.JdzcClassService;
import com.wtwd.campus.model.ClassQueryModel;
import com.wtwd.campus.model.vo.ClassesVO;
import com.wtwd.campus.model.vo.ResultVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author mjy
 * @date 2021/06/17
 * @description
 */
@Service
public class JdzcClassServiceImpl implements JdzcClassService {
    @Resource
    private JdzcClassMapper jdzcClassMapper;

    @Resource
    private JdzcTeacherMapper jdzcTeacherMapper;

    @Resource
    private JdzcStudentMapper jdzcStudentMapper;

    @Override
    public IPage<ClassesVO> queryPage(Page page, ClassQueryModel classQueryModel) {
        if (classQueryModel.getSchoolIds() == null) {
            return null;
        }
        return jdzcClassMapper.queryList(page, classQueryModel);
    }

    @Override
    public ResultVO deleteClassesById(Integer id) {
        Integer count = new LambdaQueryChainWrapper<>(jdzcTeacherMapper)
                .eq(Teacher::getManageClass, id)
                .or()
                .apply("FIND_IN_SET (" + id + ",teach_class)")
                .count();
        if (count > 0) {
            return ResultVO.error(RespCode.CLASSES_EXIST_TEACHER);
        }
        Integer studentCount = new LambdaQueryChainWrapper<>(jdzcStudentMapper)
                .eq(Student::getClassesId, id)
                .count();
        if (studentCount > 0) {
            return ResultVO.error(RespCode.CLASSES_EXIST_STUDENT);
        }
        jdzcClassMapper.deleteById(id);
        return ResultVO.ok();
    }

    @Override
    public ResultVO createClass(Classes classes) {
        String classesName = classes.getClassesName();
        Integer gradeId = classes.getGradeId();
        if (StringUtils.isBlank(classesName) || gradeId == null) {
            return ResultVO.error(RespCode.PARAMS_ERROR);
        }
        try {
            jdzcClassMapper.insert(classes);
        } catch (DuplicateKeyException e) {
            return ResultVO.ok(RespCode.GRADE_EXIST_CLASS);
        }
        return ResultVO.ok();
    }

    @Override
    public ResultVO updateClass(Classes classes) {
        if (classes.getGradeId() == null) {
            return ResultVO.error(RespCode.PARAMS_ERROR);
        }
        try {
            jdzcClassMapper.updateById(classes);
        } catch (DuplicateKeyException e) {
            return ResultVO.ok(RespCode.GRADE_EXIST_CLASS);
        }
        return ResultVO.ok();
    }

    @Override
    public Map<Integer, Integer> countClassByGradeIds(List<Integer> gradeIds) {
        if (gradeIds == null || gradeIds.size() == 0) return null;
        return jdzcClassMapper.countClassByGradeIds(gradeIds).stream()
                .collect(Collectors.toMap(item -> (Integer) item.get("gradeId"), item -> ((Long) item.get("num")).intValue()));
    }

    @Override
    public List<Classes> listClassByGradeIds(List<Integer> gradeIds) {
        return new LambdaQueryChainWrapper<>(jdzcClassMapper)
                .in(Classes::getGradeId, gradeIds)
                .list();
    }

    /**
     * value: 1/一年级/一班
     *
     * @param classIds
     * @return
     */
    @Override
    public Map<Integer, String> getClassGradeNameByClassIds(String classIds) {
        return jdzcClassMapper.listClassGradeByClassIds(classIds).stream()
                .collect(Collectors.toMap(item -> (Integer) item.get("classes_id")
                        , item -> StringUtils.joinWith(SignConstant.DELIMITER, item.get("grade_id"), item.get("grade_name"), item.get("classes_name"))));
    }

    @Override
    public Integer getClassIdByClassId(Integer id) {
        return jdzcClassMapper.getClassIdByClassId(id);
    }

    @Override
    public List<String> getImeiListByClassId(Integer classId) {
        return jdzcClassMapper.getImeiListByClassId(classId);
    }

    @Override
    public Map<String, String> getClassGradeIdByClassNames(Integer schoolId, Set<String> classNames) {
        if (classNames == null || classNames.size() == 0 || schoolId == null) return new HashMap<>();
        return jdzcClassMapper.listClassGradeByClassName(schoolId, classNames).stream()
                .collect(Collectors.toMap(item -> String.join(SignConstant.DELIMITER, (String) item.get("grade_name"), (String) item.get("classes_name"))
                        , item -> String.join(SignConstant.DELIMITER, String.valueOf(item.get("grade_id")), String.valueOf(item.get("classes_id")))));
    }

}
